<template>
	<div>

		<div>
			<el-button size="mini" type="primary" @click="customButtonClick">上传<i
					class="el-icon-upload el-icon--right"></i>
			</el-button>
			<input :ref="randomId" type="file" class="custom-input" @change='upload($event)'
				style='display: none !important;' multiple="multiple">
			<span style="float: right;width: 260px;margin-left: 30px;font-size: 12px;">
				<el-progress :percentage="progress" :color="colors" :width="80"></el-progress>
				剩余时间：{{progress==100?0:resttime}}&nbsp;&nbsp;&nbsp;
				速度：{{progress==100?0:speedUnits}}
			</span>
		</div>
		<div style="margin-top: 10px;">

			<el-input size="mini" placeholder="请输入url" v-model="insertUrl" class="input-with-select">
				<el-button slot="append" size="mini" type="primary" @click="insert">插入</el-button>
			</el-input>


		</div>
		<div style="width:100%;height:30px;"></div>
		<div style="width:100%;">
			<template v-for="(item, index) in uploadImg">
				<div :key="index" v-if="item.type=='image'"
					style="margin-bottom:10px;width:150px;height:110px;word-wrap: break-word;word-break: normal;float:left;border-bottom:1px solid gray;position:relative;margin-right:10px;">
					<div style="width:150px;height:80px;object-fit: contain;">
						<img style="object-fit: contain;width: 100%;height: 100%;" :src="item.url"></img>
					</div>
					<div style="width:150px;height:20px;padding-top: 5px;padding-left: 3px;">
						<i class="el-icon-delete" :data-index="index" @click="removeImg"></i>
						<a style="font-size: 12px;color:el-icon-document-copy" @click="copyLink(item.url,item.id)"
							:class="item.id + 'tag'">显示链接</a>
					</div>
				</div>
				<div :key="index" v-if="item.type=='vedio'"
					style="margin-bottom:10px;width:150px;height:110px;word-wrap: break-word;word-break: normal;float:left;border-bottom:1px solid gray;position:relative;margin-right:10px;">
					<div style="width:150px;height:80px;">
						<video style="object-fit: contain;width: 100%;height: 100%;" :src="item.url"
							controls="controls">
							您的浏览器不支持 video 标签。
						</video>
					</div>
					<div style="width:150px;height:20px;padding-top: 5px;padding-left: 3px;">
						<i class="el-icon-delete" :data-index="index" @click="removeImg"></i>
						<a style="font-size: 12px;color:el-icon-document-copy" @click="copyLink(item.url,item.id)"
							:class="item.id + 'tag'">显示链接</a>
					</div>
				</div>
				<div :key="index" v-if="item.type=='doc'"
					style="margin-bottom:10px;width:150px;height:110px;word-wrap: break-word;word-break: normal;float:left;border-bottom:1px solid gray;position:relative;margin-right:10px;">
					<div style="width:150px;height:80px;">
						<span>{{item.title}}</span>
					</div>
					<div style="width:150px;height:20px;padding-top: 5px;padding-left: 3px;">
						<i class="el-icon-delete" :data-index="index" @click="removeImg"></i>
						<a style="font-size: 12px;color:el-icon-document-copy" @click="copyLink(item.url,item.id)"
							:class="item.id + 'tag'">显示链接</a>
					</div>
				</div>
				<div :key="index" v-if="!item.type"
					style="margin-bottom:10px;width:150px;height:110px;word-wrap: break-word;word-break: normal;float:left;border-bottom:1px solid gray;position:relative;margin-right:10px;">
					<div style="width:150px;height:80px;">
						<span>{{item.title}}</span>
					</div>
					<div style="width:150px;height:20px;padding-top: 5px;padding-left: 3px;">
						<i class="el-icon-delete" :data-index="index" @click="removeImg"></i>
						<a style="font-size: 12px;color:el-icon-document-copy" @click="copyLink(item.url,item.id)"
							:class="item.id + 'tag'">显示链接</a>
					</div>
				</div>
			</template>
		</div>



	</div>
</template>
<script>
	import Common from './js/Common'
	import plugins from '../../register/plugin.js'
	import store from 'store/'
	import spark from '../../utils/sparkmd5.js'
	import func from '../../utils/func/func.js'
	import Clipboard from 'clipboard'
	import uploadPlugin from '../../utils/upload.js'
	import {
		gbs
	} from 'config/'
  
	export default {
    name: 'upload',
    mixins:[Common],
		data() {
			return {
				defaultProps: {
					children: 'child',
					label: 'title',
					value: 'id',
				},
				uploadImg: [],
				insertUrl: '',
				speedUnits: '0/s',
				progress: 0,
				resttime: 0,
				finishCount: 0,
				colors: [{
						color: '#f56c6c',
						percentage: 20
					},
					{
						color: '#e6a23c',
						percentage: 40
					},
					{
						color: '#5cb87a',
						percentage: 60
					},
					{
						color: '#1989fa',
						percentage: 80
					},
					{
						color: '#6f7ad3',
						percentage: 100
					}
				],
				randomId: Math.ceil(Math.random() * 10000) + 'file',
				insertUrl: '',
				fileObj: {}
			}
		},
		async created() {
			if (!this.defaultValue || !Array.isArray(this.defaultValue)) {
				this.uploadImg = []
			} else {
				if (this.defaultValue.length > 0) {
					if (this.defaultValue[0]['videoId']) {
						this.uploadImg = await this.checkAliDbVedio(this.defaultValue);
					} else {
						this.uploadImg = this.defaultValue;
					};
				};
			};

		},
		mounted() {

		},
		computed: {},
		methods: {

			customButtonClick() {
				const self = this;
				self.$refs[self.randomId].click(); //打开file 选择图片
			},


			async upload(e) {

				const self = this;

				for (var i = 0; i < e.target.files.length; i++) {
					self.fileObj = e.target.files[i];
					self.start_time = new Date().getTime();
					self.totalSize = self.fileObj.size;
					self.orginName = self.fileObj.name;
					var obj = self.fileObj.name.lastIndexOf(".");
					self.ext = self.fileObj.name.substr(obj + 1);

					//阿里云点播上传
					await uploadPlugin.ali_db_upload(self.fileObj, self.setProgress, self.insert, self.$store.getters.getToken);

				};

			},



			removeImg(e) {
				const self = this;
				var index = e.target.dataset.index;
				self.uploadImg.splice(index, 1);
				self.$emit('onChange', {
					field: self.field,
					value: self.uploadImg
				});
			},


			// 进度条
			setProgress(progress) {
				const self = this;
				self.progress = progress;
				var oloaded = self.totalSize * progress / 100;
				var nt = new Date().getTime(); //获取当前时间
				var durationTime = (nt - self.start_time) / 1000; //计算出上传到现在的时间差，单位为s

				//上传速度计算
				if (durationTime == 0) {
					return;
				};
				var speed = oloaded / durationTime; //单位b/s
				var bspeed = speed;
				var units = 'b/s'; //单位名称
				if (speed / 1024 > 1) {
					speed = speed / 1024;
					units = 'k/s';
				}
				if (speed / 1024 > 1) {
					speed = speed / 1024;
					units = 'M/s';
				}
				speed = speed.toFixed(1);
				//剩余时间
				self.resttime = (durationTime / progress * (100 - progress)).toFixed(1) + '-s';
				self.speedUnits = speed + units;

			},

			insert(url, videoId) {
				const self = this;

				var lastArray = url.split("/");
				self.orginName = lastArray[lastArray.length - 1];


				//判断文件类型渲染(H5 video标签只支持H264编码的MP4)
				var videoArray = ['mp4'];
				var imageArray = ['image', 'jpeg', 'png', 'PNG', 'JPEG', 'jpg', 'JPG'];
				var docArray = ['doc', 'xlsx', 'xls', 'csv', 'pdf', 'txt', 'ppt'];
				var type = '';
				if (videoArray.indexOf(self.ext) != -1) {
					type = 'vedio';
				} else if (imageArray.indexOf(self.ext) != -1) {
					type = 'image';
				} else if (docArray.indexOf(self.ext) != -1) {
					type = 'doc';
				} else {
					type = 'other';
				};

				self.uploadImg.push({
					url: url,
					type: type,
					videoId: videoId,
					title: self.orginName,
				});

				if (videoId) {
					var newDefault = [];
					for (var i = 0; i < self.uploadImg.length; i++) {
						newDefault.push({
							type: self.uploadImg[i]['type'],
							videoId: self.uploadImg[i]['videoId'],
							title:  self.uploadImg[i]['title']
						});
					};
					console.log('newDefault',newDefault)
					
					self.$emit('onChange', {
						field: self.field,
						value: newDefault
					});
				} else {
					self.$emit('onChange', {
						field: self.field,
						value: self.uploadImg
					});
				};


				self.insertUrl = "";
				self.resttime = 0;
				self.speedUnits = '0/s';
				if (videoId) {
					self.$emit('onChange', {
						field: {
							key: 'videoId'
						},
						value: videoId
					});
				};

			},

			copyLink(url, id) {
				const self = this;
				let clipboard = new Clipboard('.' + id + 'tag', {
					text: function() {
						return url
					}
				})
				clipboard.on('success', e => {
					func.notify('复制成功', 'success');
					clipboard.destroy()
				})
				clipboard.on('error', e => {
					func.notify('复制失败', 'warning');
					clipboard.destroy()
				})
			},

			copyUrl(index) {
				console.log(index);
				const self = this;
				self.uploadImg[index]['showUrl'] = true;
				self.$set(self.uploadImg, index, self.uploadImg[index]);
			},


			async checkAliDbVedio(uploadImg) {
				const self = this;
				var newuploadImg = self.$$cloneForm(uploadImg);
				for (var i = 0; i < newuploadImg.length; i++) {
					var res = await plugins['api_getAliPlayInfo']({
						data: {
							'videoId': newuploadImg[i].videoId
						}
					});
					newuploadImg[i]['url'] = res.PlayInfoList.PlayInfo[0]['PlayURL'];
				};
				console.log('newuploadImg', newuploadImg)
				return newuploadImg;
			},

		},
		watch: {
			async defaultValue() {
				console.log('this.defaultValue',this.defaultValue)
				if (!this.defaultValue || !Array.isArray(this.defaultValue)) {
					this.uploadImg = []
				} else {
					if (this.defaultValue.length > 0) {
						if (this.defaultValue[0]['videoId']) {
							this.uploadImg = await this.checkAliDbVedio(this.defaultValue);
						} else {
							this.uploadImg = this.defaultValue;
						};
					} else {
						this.uploadImg = this.defaultValue;
					};
				};
				console.log('this.uploadImg', this.uploadImg)
			},
		}

	}
</script>
